package com.masonluo.mlonlinejudge.service.impl;

import com.masonluo.mlonlinejudge.dao.BookRepository;
import com.masonluo.mlonlinejudge.entity.Book;
import com.masonluo.mlonlinejudge.exceptions.ResourceNotFoundException;
import com.masonluo.mlonlinejudge.mapper.BookMapper;
import com.masonluo.mlonlinejudge.model.bo.BookBo;
import com.masonluo.mlonlinejudge.model.dto.BookCreateDto;
import com.masonluo.mlonlinejudge.model.param.EditBookParam;
import com.masonluo.mlonlinejudge.service.BookService;
import com.masonluo.mlonlinejudge.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author masonluo
 * @date 2021/2/10 3:31 下午
 */
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private BookRepository bookRepository;

    @Override
    public BookBo createBook(BookCreateDto book) {
        Book b = bookMapper.createDtoToDo(book);
        bookRepository.insert(b);
        return bookMapper.doToBo(b);
    }

    @Override
    public BookBo findById(Integer id) {
        Book book = bookRepository.selectById(id);
        if (book == null) {
            throw new ResourceNotFoundException(String.format("The book [%d] does not exist.", id));
        }
        return bookMapper.doToBo(book);
    }

    @Override
    public boolean exist(Integer id) {
        return bookRepository.countById(id) > 0;
    }

    @Override
    public List<BookBo> findList() {
        List<BookBo> bos = bookMapper.doToBo(bookRepository.selectAll());
        return CollectionUtils.emptyOrOriginList(bos);
    }

    @Override
    public void delete(Integer bookId) {
        bookRepository.deleteById(bookId);
    }

    @Override
    public BookBo update(EditBookParam editBookParam) {
        if (bookRepository.update(editBookParam) > 0) {
            return new BookBo(editBookParam.getId(),
                    editBookParam.getName(),
                    editBookParam.getAuthor(),
                    editBookParam.getPublisher());
        }
        throw new ResourceNotFoundException("Fail to update the Book entity, please confirm the book exist");
    }
}
